"""
Case Type   : 资源池化
Case Name   : 扩容执行前，主机注入dss故障
Create At   : 2024.10
Owner       : chen
Description :
    1.主节点注入dss故障
    mv dss_home dsh
    kill -9 pid(dss)
    2.执行扩容
    gs_expansion -U {user} -G {user} -X {xml} -h {ip}
    3.恢复环境
    mv dsh dss_home
    cm_ctl start -n 1
Expect      :
    1.注入故障成功
    2.合理报错
    3.恢复成功
"""

import os
import unittest
import time
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from yat.test import Node
from yat.test import macro

class SharedStorage(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_root_node = Node('PrimaryRoot')
        self.pri_comsh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.db_host = Node('Standby2DbUser').db_host
        self.s_user = self.pri_node.ssh_user

    def test_shared_storage(self):
        text = '-----step1: 主节点注入dss故障 expect: 成功-----'
        self.log.info(text)
        pid = self.com.get_pid(self.sta2_node, 'bin/dssserver')
        cmd = f'''mv {macro.DSS_INSTANCE} {macro.DSS_INSTANCE}_bak'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        cmd = f'''kill -9 {pid}'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        time.sleep(5)

        text = '-----step2: 执行扩容 expect: 合理报错-----'
        self.log.info(text)
        xml_path = macro.DB_XML_PATH
        cmd = f'''gs_expansion -U {self.s_user} -G \
            {self.s_user} -X {xml_path} -h {self.db_host}'''
        execute_cmd = f'''source {macro.DB_ENV_PATH};
            expect <<EOF
            set timeout 300
            spawn {cmd}
            expect "*assword*:"
            send "{self.pri_root_node.ssh_password}\\n"
            expect "*assword*:"
            send "{self.pri_root_node.ssh_password}\\n"
            expect "*lease repeat for database*:"
            send "{macro.GAUSSDB_INIT_USER_PASSWD}\\n"
            expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        res = self.pri_root_node.sh(execute_cmd).result()
        self.log.info(res)
        self.assertIn('Failed to get old DSS_NODES_LIST', res)

    def tearDown(self):
        text = "-----step6: 恢复环境 expect: 成功-----"
        self.log.info(text)
        cmd = f'''rm -rf {macro.DSS_INSTANCE}; \
            mv {macro.DSS_INSTANCE}_bak {macro.DSS_INSTANCE}'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        res = self.pri_comsh.exec_cm_ctl('start -n 1')
        self.log.info(res)
        self.assertIn(self.constant.cm_start_instance_success_msg, res)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')